package com.letianpai.activity.family;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.letianpai.activity.LoginActivity;
import com.letianpai.activity.SelectContactsActivity;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.ReportedData;
import org.jivesoftware.smackx.ReportedData.Row;
import org.jivesoftware.smackx.search.UserSearchManager;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.letianpai.R;
import com.letianpai.db.Constant;
import com.letianpai.dialog.CustomDialog;
import com.letianpai.http.RequestBean.InviteFamily;
import com.letianpai.http.RequestBean.InviteFamilyUserBean;
import com.letianpai.service.XmppService;
import com.letianpai.utils.JsonUtil;
import com.letianpai.utils.XmppTool;

public class AddFamilyActivity extends Activity {

    private String pUSERID;// 当前用户
    private String queryResult = "";
    SimpleAdapter listItemAdapter;
    ArrayList<HashMap<String, Object>> listItem;
    TextView seek_family, headShare, headText;
    EditText friend_add;
    ImageView regist_img;
    RequestQueue requestQueue;
    View headBackText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.add_family);
        initView();
    }

    private void initView() {
        requestQueue = Volley.newRequestQueue(this);
        seek_family = (TextView) findViewById(R.id.seek_family);
        seek_family.setOnClickListener(new AddFamilyClick());
        headShare = (TextView) findViewById(R.id.headShare);
        headShare.setText("");
        headText = (TextView) findViewById(R.id.headText);
        headText.setText("邀请成员");
        headBackText = findViewById(R.id.headBackText);
        headBackText.setOnClickListener(new AddFamilyClick());
        regist_img = (ImageView) findViewById(R.id.regist_img);
        friend_add = (EditText) findViewById(R.id.friend_add);
        regist_img.setOnClickListener(new AddFamilyClick());
    }

    public void searchFriend() {
        // 获取输入信息
        final String friend_add_text = ((EditText) findViewById(R.id.friend_add))
                .getText().toString();
        if (friend_add_text.equals("")) {
            Toast.makeText(AddFamilyActivity.this, "输入信息不能为空！",
                    Toast.LENGTH_SHORT).show();
        } else {
            try {
                XMPPConnection connection = XmppTool.getConnection();
                UserSearchManager search = new UserSearchManager(connection);
                // 此处一定要加上 search.
                Form searchForm = search.getSearchForm("search."
                        + connection.getServiceName());

                Form answerForm = searchForm.createAnswerForm();
                answerForm.setAnswer("Username", true);
                answerForm.setAnswer("search", friend_add_text.toString()
                        .trim());
                ReportedData data = search.getSearchResults(answerForm,
                        "search." + connection.getServiceName());
                Iterator<Row> it = data.getRows();
                Row row = null;

                while (it.hasNext()) {
                    row = it.next();
                    queryResult = row.getValues("Username").next().toString();
                }

            } catch (Exception e) {
                Toast.makeText(AddFamilyActivity.this,
                        e.getMessage() + " " + e.getClass().toString(),
                        Toast.LENGTH_SHORT).show();
            }
            if (!queryResult.equals("")) {
                // 生成动态数组，加入数据
                listItem = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("name", queryResult); // 会员昵称
                listItem.add(map);
                final String name = queryResult;
				/*
				 * AlertDialog.Builder dialog = new AlertDialog.Builder(
				 * AddFamilyActivity.this); dialog.setTitle("添加好友")
				 * .setIcon(R.drawable.a_001) .setMessage("您确定要添加【" + name +
				 * "】为好友吗？") .setPositiveButton("确定", new
				 * DialogInterface.OnClickListener() {
				 *
				 * @Override public void onClick(DialogInterface dialog, int
				 * which) { Roster roster = XmppTool
				 * .getConnection().getRoster(); String userName = name + "@" +
				 * XmppTool.getConnection() .getServiceName(); // 默认添加到【我的好友】分组
				 * String groupName = "我的好友"; XmppService.addUsers(roster,
				 * userName, name, groupName); Presence subscription = new
				 * Presence(Presence.Type.subscribe );
				 * subscription.setTo(userName);
				 * XmppTool.con.sendPacket(subscription);
				 *
				 * Log.d("zzzz", "已经发送好友邀请了"+userName); dialog.cancel();// 取消弹出框
				 * finish(); } }) .setNegativeButton("取消", new
				 * DialogInterface.OnClickListener() { public void
				 * onClick(DialogInterface dialog, int which) { // TODO
				 * Auto-generated method // stub dialog.cancel();// 取消弹出框 }
				 * }).create().show();
				 */
                dialog(name);

            } else {
                Toast.makeText(AddFamilyActivity.this, "此用户不存在，是否邀请对方注册",
                        Toast.LENGTH_SHORT).show();
                final CustomDialog dialog = new CustomDialog(this,
                        R.layout.invite_register);
                dialog.setLeftOnClick(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                post();
                            }
                        }).start();
                        Uri smsToUri = Uri.parse("smsto:" + friend_add_text);// 联系人地址
                        Intent mIntent = new Intent(
                                android.content.Intent.ACTION_SENDTO, smsToUri);
                        mIntent.putExtra("sms_body", "短信内容");
                        startActivity(mIntent);
                        dialog.dismiss();
                    }
                });

                dialog.setRightOnClick(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    class AddFamilyClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.seek_family:
                    searchFriend();
                    break;
                case R.id.regist_img:
                    Intent intent = new Intent(AddFamilyActivity.this,
                            SelectContactsActivity.class);
                    startActivityForResult(intent, 200);
                    break;
                case R.id.headBackText:
                    finish();
                    break;
                default:
                    break;
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        friend_add.setText(data.getStringExtra("contact"));
    }

    public void post() {
        Map<String, String> map = new HashMap<String, String>();
        InviteFamily userInfo = new InviteFamily();
        userInfo.setInvite_from_username(LoginActivity.USERID);
        userInfo.setInvite_to_username(friend_add.getText().toString());
        InviteFamilyUserBean user = new InviteFamilyUserBean();
        user.setHead("inviteUserServlet");
        user.setContent(userInfo);
        // msg值
        String msg = JsonUtil.objectToString(user, InviteFamilyUserBean.class);
        String url = Constant.URL + "?msg=" + msg;
        Log.d("zzzz", url);
        StringRequest request = new StringRequest(url, new ls(), new el());
        requestQueue.add(request);
    }

    class ls implements Listener<String> {

        @Override
        public void onResponse(String arg0) {
        }

    }

    class el implements ErrorListener {

        @Override
        public void onErrorResponse(VolleyError arg0) {
            Toast.makeText(AddFamilyActivity.this, "请求失败", Toast.LENGTH_SHORT)
                    .show();
        }

    }

    protected void dialog(final String name) {
        final CustomDialog dialog = new CustomDialog(this,
                R.layout.dialog_add_family);
        View view = dialog.getCustomView();
        TextView family_dialog_detial = (TextView) view.findViewById(R.id.family_dialog_detial);
        family_dialog_detial.setText("确认添加【" + name + "】为好友吗？");
        dialog.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Roster roster = XmppTool.getConnection().getRoster();
                String userName = name + "@"
                        + XmppTool.getConnection().getServiceName();
                // 默认添加到【我的好友】分组
				/*
				 * String groupName = "我的好友"; XmppService.addUsers(roster,
				 * userName, name, groupName);
				 */
                Presence subscription = new Presence(Presence.Type.subscribe);
                subscription.setTo(userName);
                XmppTool.con.sendPacket(subscription);
                
 
				XmppService.addUserToGroup(userName, "我的好友", XmppTool.con);
                Log.d("zzzz", "已经发送好友邀请了" + userName);
                finish();
                dialog.dismiss();
            }
        });
        dialog.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
